import React, { FC, useState,
  // useEffect
} from 'react'
import  './QuestionCard.css'
import { Button,Divider,Space,Tag,Popconfirm,Modal,message } from 'antd'
import { 
  EditOutlined,
  LineChartOutlined,
  StarOutlined,
  CopyOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import { useNavigate,Link } from 'react-router-dom'
import { updateQuestionService,duplicateQuestionService } from '../service/question.ts'
import { useRequest } from 'ahooks'
// ts 自定义类型
type PropsType = {
  id: string
  title: string
  isPublished: boolean
  isStar: boolean
  answerCount: number
  createdAt: string
}
const {confirm} = Modal
// FC - functional component
const QuestionCard: FC<PropsType> = (props:any) => {
  const { id, title, createdAt, answerCount, isStar, isPublished} = props
  const nav = useNavigate()

  // useEffect(() => {
  //   console.log('question card mounted')
  //   return () => {
  //     console.log('question card unmounted', id) // 销毁
  //   }

  // 生命周期：创建，更新（state 变化），销毁
  // }, [])

  // 修改星标
  const [isStarState, setIsStarState] = useState(isStar)
  const { loading: changeStarLoading, run: changeStar } = useRequest(async ()=>{
    await updateQuestionService(id,{ isStar: !isStarState })
  },{
    manual: true,
    onSuccess(){
      setIsStarState(!isStarState)
      message.success('已更新')
    }
  })

  // 复制
  // const duplicate = ()=>{
  //   message.success('执行复制')
  // }

  const { loading:duplicateLoading, run:duplicate } = useRequest(async ()=>{
    // 方式1
    // const data = await duplicateQuestionService(id)
    // return data

    // 方式2
    return  await duplicateQuestionService(id)

    // 方式3 最简洁的方式
    // async ()=> await duplicateQuestionService(id)
  },{
    manual: true,
    onSuccess(res:any){
      message.success('复制成功')
      nav(`/question/edit/${res.id}`) // 编辑页
    }
  })

  const [ isDeletedState, setIsDeletedState ] = useState(false)
  const { loading: deleteLoading, run: deleteQuestion } = useRequest(
    async ()=> await updateQuestionService(id,{isDeleted: true}),
    {
      manual: true,
      onSuccess: ()=>{
        message.success('删除成功')
        setIsDeletedState(true)
      }
    }
  )

  

  // 删除
  const del = ()=>{
    confirm({
      title: '确定删除该问卷？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: deleteQuestion,
    })
  }

  // 已经删除的问卷，不要再渲染卡片了
  if(isDeletedState) return null
  return (
    <div className="containerQues">
      <div className="title">
        <div className="left">
          <Link to={isPublished ? `/question/stat/${id}` : `/question/edit/${id}` }>
            <Space>
              {isStarState && <StarOutlined style={{ color:'red'}} />}
              {title}
            </Space>
          </Link>
        </div>
        <div className="right">
          <Space>
            { isPublished ? <Tag color="green">已发布</Tag>  : <Tag>未发布</Tag>}
            <span>答卷: {answerCount}</span>
            <span>{createdAt}</span>
          </Space>
        </div>
      </div>
      <Divider style={{ margin: '12px' }} />
      <div className="button-container">
        <div className="left">
          <Button icon={<EditOutlined />} type="text" size="small" onClick={()=> nav(`/question/edit/${id}`)}>编辑问卷</Button>
          <Button icon={<LineChartOutlined />} type="text" size="small" onClick={()=> nav(`/question/stat/${id}`)} disabled={!isPublished}>问卷统计</Button>
        </div>
        <div className="right">
          <Space>
            <Button 
              icon={<StarOutlined />} 
              type="text" size="small" 
              onClick={changeStar} 
              disabled={changeStarLoading} >{isStarState ? '取消标星' : '标星'}</Button>
            <Popconfirm
                title="确定复制该问卷？"
                okText="确定"
                cancelText="取消"
                onConfirm={duplicate}
              >
              <Button icon={<CopyOutlined />} disabled={duplicateLoading}>复制</Button>
            </Popconfirm>
            <Button icon={<DeleteOutlined />} disabled={deleteLoading}  onClick={del}>删除</Button>
          </Space>

        </div>
      </div>
    </div>
  )
}

export default QuestionCard
